class Room < ActiveRecord::Base
  belongs_to :site
  has_and_belongs_to_many :criterias
  has_and_belongs_to_many :not_criterias, :class_name => 'Criteria', :join_table => 'not_criterias_rooms'
  has_many :beds
  
  def number_of_beds=(number_of_beds)
    number_of_beds = number_of_beds.to_i
    change = number_of_beds.to_i - self.number_of_beds.to_i
    
    self.beds.delete_all if change < 0
    
    change.times do
      self.beds << Bed.create(:occupied => false)
    end
  end
  
  def number_of_beds
    count = self.beds.count
    count == 0 ? "" : count.to_s
  end
  
  def number_of_available_beds
    self.beds.collect {|bed| bed.occupied.nil? || !bed.occupied}.count(true)
  end
  
  def occupied?
    number_of_available_beds == 0
  end
end
